# -*- coding: utf-8 -*-

import json
import logging
from odoo import http, fields
from odoo.http import request
from odoo.exceptions import UserError, ValidationError
from .api_base import APIBaseController

_logger = logging.getLogger(__name__)


class UserController(APIBaseController):
    """用户管理控制器"""



    @http.route('/api/system/user/list', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def user_list(self, **kwargs):
        """用户列表查询"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:list'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs or {}
            
            # 构建查询条件
            domain = [('del_flag', '=', '0')]
            
            # 用户名查询
            if data.get('userName'):
                domain.append(('username', 'ilike', data['userName']))
            
            # 手机号查询
            if data.get('phone'):
                domain.append(('phone', 'ilike', data['phone']))
            
            # 状态查询
            if data.get('status'):
                domain.append(('status', '=', data['status']))
            
            # 部门查询
            if data.get('deptId'):
                dept = request.env['device.department'].sudo().browse(data['deptId'])
                if dept.exists():
                    # 包含子部门
                    dept_ids = dept.get_children_departments().ids + [dept.id]
                    domain.append(('department_id', 'in', dept_ids))
            
            # 时间范围查询
            if data.get('params', {}).get('beginTime'):
                domain.append(('create_time', '>=', data['params']['beginTime']))
            if data.get('params', {}).get('endTime'):
                domain.append(('create_time', '<=', data['params']['endTime']))
            
            # 数据权限过滤
            if not current_user.is_admin:
                data_scope_dept_ids = current_user.get_data_scope_department_ids()
                if data_scope_dept_ids:
                    domain.append(('department_id', 'in', data_scope_dept_ids))
                elif current_user.get_user_data_scope() == 'self':
                    domain.append(('id', '=', current_user.id))
            
            # 分页参数
            page_num = data.get('pageNum', 1)
            page_size = data.get('pageSize', 10)
            offset = (page_num - 1) * page_size
            
            # 查询用户
            users = request.env['device.user'].sudo().search(domain, offset=offset, limit=page_size, order='create_time desc')
            total = request.env['device.user'].sudo().search_count(domain)
            
            # 构建返回数据
            rows = []
            for user in users:
                user_data = {
                    'userId': user.id,
                    'userName': user.username,
                    'nickName': user.nick_name or user.username,
                    'email': user.email,
                    'phone': user.phone,
                    'sex': '0',
                    'avatar': user.avatar or '',
                    'status': user.status,
                    'delFlag': user.del_flag,
                    'loginIp': user.login_ip,
                    'loginDate': user.login_date and user.login_date.strftime('%Y-%m-%d %H:%M:%S'),
                    'createTime': user.create_time and user.create_time.strftime('%Y-%m-%d %H:%M:%S'),
                    'remark': user.remark,
                    'dept': {
                        'deptId': user.department_id.id,
                        'deptName': user.department_id.name,
                        'leader': user.department_id.device_leader_id.nick_name if user.department_id.device_leader_id else None
                    } if user.department_id else None,
                    'roles': [{'roleId': role.id, 'roleName': role.name, 'roleKey': role.code} for role in user.role_ids],
                    'postIds': user.post_ids.ids,
                    'roleIds': user.role_ids.ids
                }
                rows.append(user_data)
            
            return {
                'code': 200,
                'msg': '查询成功',
                'data': {
                    'total': total,
                    'rows': rows
                }
            }
            
        except Exception as e:
            _logger.error(f"查询用户列表异常: {str(e)}")
            return {'code': 500, 'msg': f'查询失败: {str(e)}', 'data': None}

    @http.route('/api/system/user', type='json', auth='none', methods=['POST'], csrf=False, cors='*')
    def user_add(self, **kwargs):
        """新增用户"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:add'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 验证必填字段
            if not data.get('userName'):
                return {'code': 500, 'msg': '用户名不能为空', 'data': None}
            if not data.get('password'):
                return {'code': 500, 'msg': '密码不能为空', 'data': None}
            
            # 检查用户名是否已存在
            existing_user = request.env['device.user'].sudo().search([
                ('username', '=', data['userName']),
                ('del_flag', '=', '0')
            ], limit=1)
            if existing_user:
                return {'code': 500, 'msg': '用户名已存在', 'data': None}
            
            # 创建用户
            user_vals = {
                'username': data['userName'],
                'password': data['password'],
                'email': data.get('email'),
                'phone': data.get('phone'),
                'nick_name': data.get('nickName'),
                'status': data.get('status', '0'),
                'remark': data.get('remark'),
                'user_type': '00',
                'create_by': current_user.username
            }
            
            # 部门
            if data.get('deptId'):
                user_vals['department_id'] = data['deptId']
            
            new_user = request.env['device.user'].sudo().create(user_vals)
            
            # 分配角色
            if data.get('roleIds'):
                role_assignments = []
                for role_id in data['roleIds']:
                    role_assignments.append({
                        'device_user_id': new_user.id,
                        'role_id': role_id,
                        'assign_by': current_user.username
                    })
                request.env['device.user.role.assignment'].sudo().create(role_assignments)
            
            # 分配岗位
            if data.get('postIds'):
                new_user.sudo().write({'post_ids': [(6, 0, data['postIds'])]})
            
            return {'code': 200, 'msg': '新增成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"新增用户异常: {str(e)}")
            return {'code': 500, 'msg': f'新增失败: {str(e)}', 'data': None}

    @http.route('/api/system/user/<int:user_id>', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def user_edit(self, user_id, **kwargs):
        """修改用户"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            
            # 查找用户
            user = request.env['device.user'].sudo().browse(user_id)
            if not user.exists() or user.del_flag == '2':
                return {'code': 500, 'msg': '用户不存在', 'data': None}
            
            # 检查用户名是否已被其他用户使用
            if data.get('userName') and data['userName'] != user.username:
                existing_user = request.env['device.user'].sudo().search([
                    ('username', '=', data['userName']),
                    ('del_flag', '=', '0'),
                    ('id', '!=', user_id)
                ], limit=1)
                if existing_user:
                    return {'code': 500, 'msg': '用户名已存在', 'data': None}
            
            # 更新用户信息
            user_vals = {
                'update_by': current_user.username
            }
            
            if data.get('userName'):
                user_vals['username'] = data['userName']
            if data.get('nickName'):
                user_vals['nick_name'] = data['nickName']
            if data.get('email'):
                user_vals['email'] = data['email']
            if data.get('phone'):
                user_vals['phone'] = data['phone']
            if 'status' in data:
                user_vals['status'] = data['status']
            if 'remark' in data:
                user_vals['remark'] = data['remark']
            if data.get('deptId'):
                user_vals['department_id'] = data['deptId']
            
            user.sudo().write(user_vals)
            
            # 更新密码
            if data.get('password'):
                user.sudo().write({'password': data['password']})
            
            # 更新角色分配
            if 'roleIds' in data:
                # 删除现有角色分配
                user.role_assignment_ids.sudo().unlink()
                # 创建新的角色分配
                if data['roleIds']:
                    role_assignments = []
                    for role_id in data['roleIds']:
                        role_assignments.append({
                            'device_user_id': user.id,
                            'role_id': role_id,
                            'assign_by': current_user.username
                        })
                    request.env['device.user.role.assignment'].sudo().create(role_assignments)
            
            # 更新岗位
            if 'postIds' in data:
                user.sudo().write({'post_ids': [(6, 0, data['postIds'])]})
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改用户异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}

    @http.route('/api/system/user/<int:user_id>', type='json', auth='none', methods=['DELETE'], csrf=False, cors='*')
    def user_delete(self, user_id, **kwargs):
        """删除用户"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:remove'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            # 查找用户
            user = request.env['device.user'].sudo().browse(user_id)
            if not user.exists():
                return {'code': 500, 'msg': '用户不存在', 'data': None}
            
            # 不能删除自己
            if user.id == current_user.id:
                return {'code': 500, 'msg': '不能删除自己', 'data': None}
            
            # 不能删除超级管理员
            if user.is_admin:
                return {'code': 500, 'msg': '不能删除超级管理员', 'data': None}
            
            # 逻辑删除
            user.sudo().write({
                'del_flag': '2',
                'status': '1',  # 停用
                'update_by': current_user.username
            })
            
            return {'code': 200, 'msg': '删除成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"删除用户异常: {str(e)}")
            return {'code': 500, 'msg': f'删除失败: {str(e)}', 'data': None}

    @http.route('/api/system/user/resetPwd', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def reset_password(self, **kwargs):
        """重置密码"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:resetPwd'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            user_id = data.get('userId')
            password = data.get('password')
            
            if not user_id or not password:
                return {'code': 500, 'msg': '参数错误', 'data': None}
            
            # 查找用户
            user = request.env['device.user'].sudo().browse(user_id)
            if not user.exists() or user.del_flag == '2':
                return {'code': 500, 'msg': '用户不存在', 'data': None}
            
            # 重置密码
            user.sudo().set_password(password)
            user.sudo().write({
                'update_by': current_user.username
            })
            
            return {'code': 200, 'msg': '重置成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"重置密码异常: {str(e)}")
            return {'code': 500, 'msg': f'重置失败: {str(e)}', 'data': None}

    @http.route('/api/system/user/changeStatus', type='json', auth='none', methods=['PUT'], csrf=False, cors='*')
    def change_status(self, **kwargs):
        """修改用户状态"""
        try:
            # 验证token
            current_user = self.verify_token()
            if not current_user:
                return {'code': 401, 'msg': '无效的访问令牌', 'data': None}
            
            # 检查权限
            if not self.check_permission('system:user:edit'):
                return {'code': 403, 'msg': '没有权限', 'data': None}
            
            data = kwargs
            user_id = data.get('userId')
            status = data.get('status')
            
            if not user_id or status is None:
                return {'code': 500, 'msg': '参数错误', 'data': None}
            
            # 查找用户
            user = request.env['device.user'].sudo().browse(user_id)
            if not user.exists() or user.del_flag == '2':
                return {'code': 500, 'msg': '用户不存在', 'data': None}
            
            # 不能修改超级管理员状态
            if user.is_admin:
                return {'code': 500, 'msg': '不能修改超级管理员状态', 'data': None}
            
            # 修改状态
            user.sudo().write({
                'status': status,
                'update_by': current_user.username
            })
            
            return {'code': 200, 'msg': '修改成功', 'data': None}
            
        except Exception as e:
            _logger.error(f"修改状态异常: {str(e)}")
            return {'code': 500, 'msg': f'修改失败: {str(e)}', 'data': None}
